package com.lego.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lego.service.UserService;
import com.lego.service.impl.UserServiceImpl;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
	UserService userService = new UserServiceImpl();
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// TODO Auto-generated method stub
		response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");
	    PrintWriter out = response.getWriter();
	    
	    String userName = request.getParameter("userName");
	    String password = request.getParameter("password");
	    String rePassword = request.getParameter("rePassword");
	    String phoneNum = request.getParameter("phoneNum");
	 //检查用户名是否为空
	    if (userName == null || userName.trim().isEmpty()) {
	        String jsonResponse = "用户名不能为空";
	        request.setAttribute("uName", jsonResponse);
	        request.getRequestDispatcher("login.jsp").forward(request, response);
	        return;
	    }
	    
	 //检查两次密码是否一致
	    if (!password.equals(rePassword)) {
	        String jsonResponse = "两次密码输入不一致";
	        request.setAttribute("passwordE", jsonResponse);
	        request.getRequestDispatcher("login.jsp").forward(request, response);
	        return;
	    }
	    try {
	        int result = userService.userRegister(userName, password, phoneNum);
	        System.out.println(result);
	        if (result == -1) {
	            String jsonResponse = "用户名已存在";
	            request.setAttribute("uName", jsonResponse);
	            request.getRequestDispatcher("login.jsp").forward(request, response);
	        } else if (result > 0) {
	        	request.getRequestDispatcher("login.jsp").forward(request,response);
	        } else {
	            String jsonResponse = "注册失败，请稍后再试";
	            request.getRequestDispatcher("login.jsp").forward(request,response);
	        }
	    } catch (Exception e) {
	        String jsonResponse = "{\"status\":\"error\", \"message\":\"系统错误: " + e.getMessage() + "\"}";
	        request.getRequestDispatcher("login.jsp").forward(request,response);
	    }
	    out.flush();
	}

}
